//
//  PywUploadAccountLoginManager.m
//  PywSdk
//
//  Created by Ampaw on 2017/6/19.
//  Copyright © 2017年 Jade. All rights reserved.
//

#import "PywUploadAccountLoginManager.h"
#import "PywPlatformMain.h"
#import "PywUploadAccountLoginTimeLong.h"
#import "PywUploadAccountLoginTimeApi.h"

@interface PywUploadAccountLoginManager ()
@property (nonatomic, strong) PywUploadAccountLoginTimeApi *uploadAccountLoginTimeApi;
@end

@implementation PywUploadAccountLoginManager
{
    NSTimer *multiCycleTimer;   // 多循环定时器
}

+ (PywUploadAccountLoginManager *)manager
{
    static id manager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[[self class] alloc] init];
    });
    return manager;
}

/**
 保存账号登录开始时间
 */
- (void)saveAccountLoginStartTime
{
    // 开启多循环定时器
//    [multiCycleTimer setFireDate:[NSDate distantPast]];
    
    NSArray *accountLoginLongs = [PywUploadAccountLoginTimeLong accountLoginLongs];
    if (accountLoginLongs.count > 0) {
        for (PywUploadAccountLoginTimeLong *accountLoginLong in accountLoginLongs) {
            // 当前账号已有缓存,当缓存中，开始时间不等于当前时间，并且结束时间等于0时，当做新数据缓存
            if ([accountLoginLong.account isEqualToString:[PywPlatformMain sharedPlatformMain].account]
                && ![accountLoginLong.startTime isEqualToString:[self getCurrentTimestamp]]
                && accountLoginLong.endTime.length == 0) {

                PywUploadAccountLoginTimeLong *accountLoginLong = [[PywUploadAccountLoginTimeLong alloc] init];
                accountLoginLong.account = [PywPlatformMain sharedPlatformMain].account;
                accountLoginLong.startTime = [PywPlatformMain sharedPlatformMain].startTime;
                [PywUploadAccountLoginTimeLong saveAccountLoginLong:accountLoginLong];
                
            // 没有缓存记录该账号，直接缓存
            }else if (![accountLoginLong.account isEqualToString:[PywPlatformMain sharedPlatformMain].account]){
                
                PywUploadAccountLoginTimeLong *accountLoginLong = [[PywUploadAccountLoginTimeLong alloc] init];
                accountLoginLong.account = [PywPlatformMain sharedPlatformMain].account;
                accountLoginLong.startTime = [PywPlatformMain sharedPlatformMain].startTime;
                [PywUploadAccountLoginTimeLong saveAccountLoginLong:accountLoginLong];
            }
        }
    }else {
        
        PywUploadAccountLoginTimeLong *accountLoginLong = [[PywUploadAccountLoginTimeLong alloc] init];
        accountLoginLong.account = [PywPlatformMain sharedPlatformMain].account;
        accountLoginLong.startTime = [PywPlatformMain sharedPlatformMain].startTime;
        [PywUploadAccountLoginTimeLong saveAccountLoginLong:accountLoginLong];
    }
}

/**
 保存账号登录结束时间
    1. 切换后台运行时，记录登录“结束”时间；
    2. 退出应用时，记录登录“结束”时间；
    3. 注销时，记录登录“结束”时间
 */
- (void)saveAccountLoginEndTime
{
    NSArray *accountLoginLongs = [PywUploadAccountLoginTimeLong accountLoginLongs];
    if (accountLoginLongs.count > 0){
        for (PywUploadAccountLoginTimeLong *accountLoginLong in accountLoginLongs) {
            if ([accountLoginLong.account isEqualToString:[PywPlatformMain sharedPlatformMain].account]
                && [accountLoginLong.startTime isEqualToString:[PywPlatformMain sharedPlatformMain].startTime]) {
                
                accountLoginLong.endTime = [self getCurrentTimestamp];
                [PywUploadAccountLoginTimeLong saveAccountLoginLong:accountLoginLong];
            }else{
               
                PywUploadAccountLoginTimeLong *accountLoginLong = [[PywUploadAccountLoginTimeLong alloc] init];
                accountLoginLong.account = [PywPlatformMain sharedPlatformMain].account;
                accountLoginLong.startTime = [PywPlatformMain sharedPlatformMain].startTime;
                accountLoginLong.endTime = [self getCurrentTimestamp];
                [PywUploadAccountLoginTimeLong saveAccountLoginLong:accountLoginLong];
            }
        }
    }else{
        
        PywUploadAccountLoginTimeLong *accountLoginLong = [[PywUploadAccountLoginTimeLong alloc] init];
        accountLoginLong.account = [PywPlatformMain sharedPlatformMain].account;
        accountLoginLong.startTime = [PywPlatformMain sharedPlatformMain].startTime;
        accountLoginLong.endTime = [self getCurrentTimestamp];
        [PywUploadAccountLoginTimeLong saveAccountLoginLong:accountLoginLong];
    }
    
    [multiCycleTimer invalidate];
    multiCycleTimer = nil;
}

/**
 上传登录时长成功后，移除该账号登录时长缓存
 */
- (void)removeAccountLoginTimeLong
{
    NSArray *accountLoginLongs = [PywUploadAccountLoginTimeLong accountLoginLongs];
    for (PywUploadAccountLoginTimeLong *accountLoginLong in accountLoginLongs) {
        if ([accountLoginLong.account isEqualToString:[PywPlatformMain sharedPlatformMain].account]
            && accountLoginLong.startTime.length > 0
            && accountLoginLong.endTime.length > 0) {
            [PywUploadAccountLoginTimeLong removeAccountLoginLong:accountLoginLong.account];
        }
    }
}

/**
 上报游戏账号登录时长
 */
- (void)uploadAccountLoginTimeLong
{
    // 将登陆成功时间，存储到内存中
    [PywPlatformMain sharedPlatformMain].startTime = [self getCurrentTimestamp];
//    PLog(@"\n\n************上报登录时长************\n\n");
    // 上报接口是否开启
    if ([PywPlatformMain sharedPlatformMain].collect_open) {
        [multiCycleTimer invalidate];
        multiCycleTimer = nil;
        
        // 非实时上报，此时等下一次登录激活时上报数据
        if ([PywPlatformMain sharedPlatformMain].collect_interval == -1) {
            
            // 进入执行一次，之后间隔时间段在执行
            [self changeLoginAccountUploadLoginTime];
            
            // 注：创建timer的同时就已经开始倒计时了，每隔3分钟自动调用changeLoginAccountUploadLoginTime，不用启动timer
            multiCycleTimer = [NSTimer scheduledTimerWithTimeInterval:180.0
                                                               target:self
                                                             selector:@selector(changeLoginAccountUploadLoginTime)
                                                             userInfo:nil
                                                              repeats:YES];
        }else{ // 实时上报模式
            
            // 进入执行一次，之后间隔时间段在执行
            [self multiCycleTimerAction];
            
            // 注：创建timer的同时就已经开始倒计时了，每隔指定时间自动调用multiCycleTimerAction，不用启动timer
            multiCycleTimer = [NSTimer scheduledTimerWithTimeInterval:[PywPlatformMain sharedPlatformMain].collect_interval * 60.0
                                                               target:self
                                                             selector:@selector(multiCycleTimerAction)
                                                             userInfo:nil
                                                              repeats:YES];
        }
    }
}

/**
 非实时上报，改变登录账号时，上报数据
 */
- (void)changeLoginAccountUploadLoginTime
{
    NSArray *accountLoginLongs = [PywUploadAccountLoginTimeLong accountLoginLongs];
    if (accountLoginLongs.count > 0) {
        PywUploadAccountLoginTimeLong *accountLoginLong = accountLoginLongs.lastObject;
        if (![accountLoginLong.account isEqualToString:[PywPlatformMain sharedPlatformMain].account]) {
            // 此时，登录其他账号激活，应上报登录时长
            NSMutableArray *parameterList = [NSMutableArray array];
            for (PywUploadAccountLoginTimeLong *accountLoginLong in accountLoginLongs) {
                MutableDictionary *param = [[MutableDictionary alloc] init];
                [param setObject:accountLoginLong.account forKey:@"account"];
                [param setObject:accountLoginLong.startTime forKey:@"startTime"];
                [param setObject:accountLoginLong.endTime forKey:@"endTime"];
                [parameterList addObject:param];
            }
            
            // 上报登录时长
            [self.uploadAccountLoginTimeApi requestUploadAccountLoginTimeWithParameterList:parameterList success:^(NSString *status, id anyObjct) {
                
                PLog(@"****上报登录时长成功****");
                [self removeAccountLoginTimeLong];
            } fail:^(NSError *error) {
                
                PLog(@"****上报登录时长失败****");
                [self saveAccountLoginStartTime];
            }];
        }else{
            
            [self cacheUploadTimeLong];
        }
        
    }else{
        
        [self cacheUploadTimeLong];
    }
    
}

/**
 实时上报模式，循环器：每隔指定时间自动调用该方法
 */
- (void)multiCycleTimerAction
{
    // 上报登录时长列表
    NSMutableArray *parameterList = [NSMutableArray array];
    
    NSArray *accountLoginLongs = [PywUploadAccountLoginTimeLong accountLoginLongs];
    if (accountLoginLongs.count > 0) {
        for (PywUploadAccountLoginTimeLong *accountLoginLong in accountLoginLongs) {
            // 存在缓存数据时，上报之前先保存该账号登录结束时间
            if ([accountLoginLong.account isEqualToString:[PywPlatformMain sharedPlatformMain].account]
                && [accountLoginLong.startTime isEqualToString:[PywPlatformMain sharedPlatformMain].startTime]) {
                
                accountLoginLong.endTime = [self getCurrentTimestamp];
                [PywUploadAccountLoginTimeLong saveAccountLoginLong:accountLoginLong];
            }
            
            if ([accountLoginLong.account isEqualToString:[PywPlatformMain sharedPlatformMain].account]
                && [accountLoginLong.startTime isEqualToString:[PywPlatformMain sharedPlatformMain].startTime]
                && accountLoginLong.endTime.length > 0) {
                
                // 上传当前登录账号登录时长
                MutableDictionary *param = [[MutableDictionary alloc] init];
                [param setObject:accountLoginLong.account forKey:@"account"];
                [param setObject:accountLoginLong.startTime forKey:@"startTime"];
                [param setObject:accountLoginLong.endTime forKey:@"endTime"];
                [parameterList addObject:param];
            }else{
                
                MutableDictionary *param = [[MutableDictionary alloc] init];
                [param setObject:[PywPlatformMain sharedPlatformMain].account forKey:@"account"];
                [param setObject:[PywPlatformMain sharedPlatformMain].startTime forKey:@"startTime"];
                [param setObject:[self getCurrentTimestamp] forKey:@"endTime"];
                [parameterList addObject:param];
            }
        }
    }else{
        
        MutableDictionary *param = [[MutableDictionary alloc] init];
        [param setObject:[PywPlatformMain sharedPlatformMain].account forKey:@"account"];
        [param setObject:[PywPlatformMain sharedPlatformMain].startTime forKey:@"startTime"];
        [param setObject:[self getCurrentTimestamp] forKey:@"endTime"];
        [parameterList addObject:param];
    }
    
    // 第一次登陆时，上报内存中的登陆时长数据
    [self.uploadAccountLoginTimeApi requestUploadAccountLoginTimeWithParameterList:parameterList success:^(NSString *status, id anyObjct) {
        
        PLog(@"****上报登录时长成功****");
        [self removeAccountLoginTimeLong];
    } fail:^(NSError *error) {
        
        PLog(@"****上报登录时长失败****");
        [self saveAccountLoginStartTime];
    }];
}

/**
 非实时上报，缓存上报时长
 */
- (void)cacheUploadTimeLong
{
    NSArray *accountLoginLongs = [PywUploadAccountLoginTimeLong accountLoginLongs];
    if (accountLoginLongs.count > 0) {
        for (PywUploadAccountLoginTimeLong *accountLoginLong in accountLoginLongs) {
            
            // 存在缓存数据时，保存该账号登录结束时间
            if ([accountLoginLong.account isEqualToString:[PywPlatformMain sharedPlatformMain].account]
                && [accountLoginLong.startTime isEqualToString:[PywPlatformMain sharedPlatformMain].startTime]) {
                
                accountLoginLong.endTime = [self getCurrentTimestamp];
                [PywUploadAccountLoginTimeLong saveAccountLoginLong:accountLoginLong];
            }else if ([accountLoginLong.account isEqualToString:[PywPlatformMain sharedPlatformMain].account]
                      && ![accountLoginLong.startTime isEqualToString:[PywPlatformMain sharedPlatformMain].startTime]){
                
                PywUploadAccountLoginTimeLong *accountLoginLong = [[PywUploadAccountLoginTimeLong alloc] init];
                accountLoginLong.account = [PywPlatformMain sharedPlatformMain].account;
                accountLoginLong.startTime = [PywPlatformMain sharedPlatformMain].startTime;
                [PywUploadAccountLoginTimeLong saveAccountLoginLong:accountLoginLong];
            }
        }
    }else {
        
        PywUploadAccountLoginTimeLong *accountLoginLong = [[PywUploadAccountLoginTimeLong alloc] init];
        accountLoginLong.account = [PywPlatformMain sharedPlatformMain].account;
        accountLoginLong.startTime = [PywPlatformMain sharedPlatformMain].startTime;
        [PywUploadAccountLoginTimeLong saveAccountLoginLong:accountLoginLong];
    }
}

//获取当前时间,转换为毫秒时间戳
- (NSString *)getCurrentTimestamp
{
    NSDate *date = [NSDate date];
    NSTimeInterval timeInterval =[date timeIntervalSince1970];
    NSString *timeStamp = [[NSString alloc] initWithFormat:@"%ld", (long)(timeInterval * 1000)];;
    return timeStamp;
}

- (PywUploadAccountLoginTimeApi *)uploadAccountLoginTimeApi
{
    if (!_uploadAccountLoginTimeApi) {
        _uploadAccountLoginTimeApi = [PywUploadAccountLoginTimeApi manager];
    }
    return _uploadAccountLoginTimeApi;
}

@end
